package cn.wjx.taobaounion.presenter.impl;

import cn.wjx.taobaounion.model.Api;
import cn.wjx.taobaounion.model.domain.Categories;
import cn.wjx.taobaounion.presenter.IHomePresenter;
import cn.wjx.taobaounion.utils.LogUtils;
import cn.wjx.taobaounion.utils.RetrofitManager;
import cn.wjx.taobaounion.view.IHomeCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * @author WuChangJian
 * @date 2020/6/17 10:58
 */
public class HomePresenterImpl implements IHomePresenter {

    private IHomeCallback mIHomeCallback;

    @Override
    public void getCategories() {
        if (mIHomeCallback != null) {
            mIHomeCallback.onLoading();
        }
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        Call<Categories> call = api.getCategories();
        call.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                LogUtils.d(HomePresenterImpl.this, "response code -- > " + response.code());
                if (response.code() == HTTP_OK) {
                    Categories categories = response.body();
                    if (mIHomeCallback != null) {
                        if (categories == null || categories.getData().size() == 0) {
                            mIHomeCallback.onEmpty();
                        } else {
                            mIHomeCallback.onCategoriesLoaded(categories);
                        }
                    }
                } else {
                    // 请求失败
                    LogUtils.d(HomePresenterImpl.this, "请求失败");
                    if (mIHomeCallback != null) {
                        mIHomeCallback.onError();
                    }
                }
            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                LogUtils.e(HomePresenterImpl.this, "onFailure-->" + t.getMessage());
                if (mIHomeCallback != null) {
                    mIHomeCallback.onError();
                }
            }
        });
    }

    @Override
    public void registerViewCallback(IHomeCallback homeCallback) {
        this.mIHomeCallback = homeCallback;
    }

    @Override
    public void unregisterViewCallback(IHomeCallback homeCallback) {
        this.mIHomeCallback = null;
    }
}
